package com.common.library.widget;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.library.listener.OnProcessListener;
import com.zs4gamesdk.R;
import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.Zs4GameMenu;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.Zs4GameData;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;

import java.util.Timer;
import java.util.TimerTask;

import static com.zs4sdk.Zs4GameBase.getPackageName;

/**
 * function: 悬浮菜单
 *
 * @ author: aXiBa
 */
public class SDKGameStartMenu extends SDKGameBaseMenu {

    private static final String TAG = SDKGameStartMenu.class.getSimpleName();

    private float x;
    private float y;
    private float StartX;
    private float StartY;

    int width_show = 0;
    int height_show = 0;

    private LinearLayout mLlFloatMenuLeft;
    private LinearLayout mLlFloatMenu;
    private FrameLayout mFlFloatLogo;
    private TextView mPayTextView,mAccountTextView,mFeedBackTextView;

    private final int HANDLER_TYPE_HIDE_LOGO = 2;//隐藏LOGO时间
    private final int HANDLER_TYPE_CANCEL_ANIM = 4;//退出动画时间

    Context mContext;
    String pageName = "";
    WindowManager mWindowManager;
    EventHandler mEventHandler;

    private Timer mTimer;
    private String menu_flag =
            getPackageName().concat(Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_MENU);

    ImageView imageView;

    TextView mSDKMenuView1, mSDKMenuView2;

    private boolean move = true;

    static int mDuckType = Zs4GameBase.DUCKPOSITION_RIGHTBOTTOM;

    public SDKGameStartMenu(Context mContext, String pageName, WindowManager mWindowManager, EventHandler mEventHandler) {

        this.mContext = mContext;
        this.pageName = pageName;
        this.mWindowManager = mWindowManager;
        this.mEventHandler = mEventHandler;
    }

    @Override
    public View getView() {

        if (null == mView) {

            // 调整范围
            setShowBound();

            createView();
        }

        return mView;
    }


    @Override
    public LayoutParams getWindowLayoutParams(int x, int y) {


//		if(null == wmParams) {
        createWindowLayoutParams(x, y);
//		}

        return wmParams;
    }


    // 屏幕改变时，重新创建view
    @Override
    public void onScreenOrientationChange() {
        // 调整范围
        setShowBound();

        createView();

        createWindowLayoutParams(wmParams.x, wmParams.y);
    }


    /**
     * 定时隐藏float view
     */
    private void timerForHide() {
        final int time;

        if (!isShowFloat()) {
            time = HANDLER_TYPE_HIDE_LOGO;
        } else {
            time = HANDLER_TYPE_CANCEL_ANIM;
        }

        if (Helper.isNotNull(mTimer)) {
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = time;
                message.arg1 = mDuckType;
                mHandler.sendMessage(message);
            }
        }, time * 1000);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HANDLER_TYPE_CANCEL_ANIM) {
                hiadSelect();
                timerForHide();
            } else if (msg.what == HANDLER_TYPE_HIDE_LOGO) {
                sethalebackground();
                if (Helper.isNotNull(mTimer)) {
                    mTimer.cancel();
                    mTimer = null;
                }
            }
        }
    };

    private void showSelect() {
        mLlFloatMenu.setVisibility(View.VISIBLE);
    }

    private void hiadSelect() {
        mLlFloatMenu.setVisibility(View.GONE);
//        mLlFloatMenuRight.setVisibility(View.GONE);
    }


    /**
     * function: 创建view
     *
     * @ author: aXiBa 2013-3-26 上午11:05:48
     */
    private void createView() {

        LayoutInflater inflater = LayoutInflater.from(mContext);
        // 从布局文件获取浮动窗口视图
        View rootFloatView = inflater.inflate(ActivityHelper.getLayoutResId("zs4gamelayout_menu_float"), null);
        mFlFloatLogo = (FrameLayout) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_fly_float_view"));
        imageView = (ImageView) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_imv_menu_float"));
        mLlFloatMenuLeft = (LinearLayout) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_lin_menu_content_left"));
        mLlFloatMenu = (LinearLayout) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_lin_menu_content"));
        mPayTextView = (TextView) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_menu_txv_pay"));

//        mPayTextView.setVisibility(View.GONE);

        mAccountTextView = (TextView) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_menu_txv_account"));
        mFeedBackTextView = (TextView) rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_menu_txv_feedback"));


        mPayTextView.setOnClickListener(clickListener);
        mAccountTextView.setOnClickListener(clickListener);
        mFeedBackTextView.setOnClickListener(clickListener);


        mSDKMenuView1 = (TextView)rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_view_menu_1"));
        mSDKMenuView2 = (TextView)rootFloatView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_view_menu_2"));

//        imageView = new ImageView(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);


        setBackground();
        rootFloatView.setLayoutParams(params);

//        imageView.setOutlineProvider();

        imageView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

//                ActivityHelper.showToast(""+event.getAction());

                // 获取到状态栏的高度
                Rect frame = new Rect();
                imageView.getWindowVisibleDisplayFrame(frame);
                int statusBarHeight = frame.top;
//				LogUtil.i(TAG, "statusBarHeight: " + statusBarHeight);

                // 获取相对屏幕的坐标，即以屏幕左上角为原点
//				x = event.getRawX() - statusBarHeight;
                x = event.getRawX();
                y = event.getRawY() - statusBarHeight;
                // LogUtil.i("currP", "currX" + x + "====currY" + y);// 调试信息
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (Helper.isNotNull(mTimer)) {
                            mTimer.cancel();
                            mTimer = null;
                        }
                        if(isShowFloat()){
                            hiadSelect();
                            move = false;
                        }else {move = true;}
                        StartX = x;
                        StartY = y;
                        // 获取相对View的坐标，即以此View左上角为原点
                        setBackground();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if(isShowFloat()){
                            hiadSelect();
//                            move = true;
                        }
                        updateViewPosition(x - getView().getWidth() / 2, y - getView().getHeight() / 2);
                        break;

                    case MotionEvent.ACTION_UP:

                        setBackground();

                        ajustViewPosition(x, y - getView().getHeight() / 2);
                        // 点击
                        if (Math.abs(x - StartX) < getView().getWidth() / 2 && Math.abs(y - StartY) < getView().getHeight() / 2) {

                            if(Zs4GameData.getInstance().isLogined()) {
//                                if (Zs4GameData.getInstance().isGuest()) {
//                                    if (null != mEventHandler) {
//                                        mEventHandler.clickHandler();
//                                    }
//                                } else {
                                    if (isShowFloat()) {
                                        hiadSelect();
                                    } else if (!isShowFloat() && move) {
                                        showSelect();
                                        move = false;
                                    }

                                    if (Helper.isNotNull(mTimer)) {
                                        mTimer.cancel();
                                        mTimer = null;
//                                    }
                                    timerForHide();
                                }
                            }else {
                                String loginStr = mContext.getString(R.string.float_login_first);
                                ActivityHelper.showToast(loginStr);
                                Zs4GameBase.getInstance().login(mContext, new OnProcessListener() {
                                    @Override
                                    public void finishProcess(int code, Bundle bundle) {

                                    }
                                });
                            }

                        }
                        break;

                    case MotionEvent.ACTION_OUTSIDE:
                        hiadSelect();
                        move = true;
                        break;
                }
                return true;
            }
        });

        mView = rootFloatView;
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //支付页面
            if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_menu_txv_pay")) {
//                Zs4GameMenu.enterVoucherCenter(mContext, menu_flag, pageName, "","");
            }
            //账号中心页面
            else if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_menu_txv_account")) {
                Zs4GameMenu.enterAccountCenter(mContext, menu_flag, pageName);
            }
            //客服页面
            else if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_menu_txv_feedback")) {
                String clientStr = mContext.getString(R.string.online_customer);
                Log.e("menu"," clientStr is "+clientStr);
                Zs4GameMenu.showWebView(mContext,
                        clientStr,
                        Extra.URL.SDKGAME_FEEDBACK,
                        menu_flag,
                        "3");
            }
        }
    };

    /**
     * 刷新float view menu
     */
    private void refreshFloatMenu() {
        if (!Zs4GameData.getInstance().isMenuLeft()) {
            FrameLayout.LayoutParams paramsFloatImage = (FrameLayout.LayoutParams) imageView.getLayoutParams();
            paramsFloatImage.setMargins(0, 0, 0, 0);
            paramsFloatImage.gravity = Gravity.RIGHT;
            imageView.setLayoutParams(paramsFloatImage);
            FrameLayout.LayoutParams paramsFlFloat = (FrameLayout.LayoutParams) mFlFloatLogo.getLayoutParams();
            paramsFlFloat.gravity = Gravity.RIGHT;
            mFlFloatLogo.setLayoutParams(paramsFlFloat);

            mLlFloatMenuLeft.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_float_bg"));

            int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, mContext.getResources().getDisplayMetrics());
            int padding52 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, mContext.getResources().getDisplayMetrics());
            LinearLayout.LayoutParams paramsMenuAccount = (LinearLayout.LayoutParams) mSDKMenuView1.getLayoutParams();
            paramsMenuAccount.rightMargin = padding;
            paramsMenuAccount.leftMargin = padding;
            mSDKMenuView1.setLayoutParams(paramsMenuAccount);

            LinearLayout.LayoutParams paramsMenuFb = (LinearLayout.LayoutParams) mSDKMenuView2.getLayoutParams();
            paramsMenuFb.rightMargin = padding52;
            paramsMenuFb.leftMargin = padding;
            mSDKMenuView2.setLayoutParams(paramsMenuFb);
        } else {
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView.getLayoutParams();
            params.gravity = Gravity.LEFT;
            imageView.setLayoutParams(params);
            FrameLayout.LayoutParams paramsFlFloat = (FrameLayout.LayoutParams) mFlFloatLogo.getLayoutParams();
            paramsFlFloat.gravity = Gravity.LEFT;
            mFlFloatLogo.setLayoutParams(paramsFlFloat);

            mLlFloatMenuLeft.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_float_bg"));
//            mLlFloatMenuLeft.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gamedraw_conner_menuleft_90_bg"));

            int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, mContext.getResources().getDisplayMetrics());
            int padding52 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, mContext.getResources().getDisplayMetrics());

            LinearLayout.LayoutParams paramsMenuAccount = (LinearLayout.LayoutParams) mSDKMenuView1.getLayoutParams();
            paramsMenuAccount.rightMargin = padding;
            paramsMenuAccount.leftMargin = padding52;
            mSDKMenuView1.setLayoutParams(paramsMenuAccount);

            LinearLayout.LayoutParams paramsMenuFb = (LinearLayout.LayoutParams) mSDKMenuView2.getLayoutParams();
            paramsMenuFb.rightMargin = padding;
            paramsMenuFb.leftMargin = padding;
            mSDKMenuView2.setLayoutParams(paramsMenuFb);
        }
    }

    private boolean isShowFloat(){
        if(mLlFloatMenu.getVisibility() == View.GONE){
            return false;
        }else {
            return true;
        }
    }


    //设置悬浮窗图片
    private void setBackground() {
        imageView.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_btn_menu"));
    }

    private void sethalebackground() {
        //未登录或者是游客登录或者客服有消息提示时
//        if ((!Zs4GameData.getInstance().isLogined())||
//                Zs4GameData.getInstance().getLoginType().equals(Extra.SDKGAMESTRS.LOING_GUEST)||
//                Zs4GameData.getInstance().getCountKefuMessage()>0) {
        if (Zs4GameData.getInstance().isMenuLeft()) {
            imageView.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_btn_menu_left"));
        } else {
            imageView.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_btn_menu_right"));
        }
//        } else {
//            imageView.setBackgroundResource(Helper.getImageResId(mContext, pageName, "zs4gameicon_menu_btn_menu"));
//        }
    }

    /**
     * function:
     *
     * @ author: aXiBa 2013-3-26 上午11:06:01
     */
    private void createWindowLayoutParams(int x, int y) {

        wmParams = new LayoutParams();
        wmParams.type = LayoutParams.TYPE_PHONE;   // 设置window type
        wmParams.format = PixelFormat.RGBA_8888;   // 设置图片格式，效果为背景透明

        wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
//    	wmParams.screenOrientation = screenOrientation;   // 设置了方向的话与HOME页面方向不一样，按HOME键和back键时会报错

        if (x < width_show / 2) {
            wmParams.x = 0;
            wmParams.y = y;
        } else {
            wmParams.x = width_show;
            wmParams.y = y;
        }
        wmParams.width = LayoutParams.WRAP_CONTENT;
        wmParams.height = LayoutParams.WRAP_CONTENT;

        timerForHide();
    }

    /**
     * function: 设置大小，边界
     *
     * @ author: aXiBa 2013-3-26 上午11:06:51
     */
    private void setShowBound() {

        int screenOrientation = mContext.getResources().getConfiguration().orientation;
//		LogUtil.i(TAG, "当前屏幕方向： " + screenOrientation);

        // 调整悬浮窗口至右下角
        Display display = mWindowManager.getDefaultDisplay();
//		LogUtil.i(TAG, "display.getWidth(): " + display.getWidth() + "    display.getHeight(): " + display.getHeight());

        int width_screen = display.getWidth();
        int height_screen = display.getHeight();

        if (Zs4GameBase.SCREEN_ORIENTATION_PORTRAIT == screenOrientation) {
            width_show = width_screen < height_screen ? width_screen : height_screen;
            height_show = width_screen < height_screen ? height_screen : width_screen;
        } else {
            width_show = width_screen < height_screen ? height_screen : width_screen;
            height_show = width_screen < height_screen ? width_screen : height_screen;
        }
    }


    /**
     * function: 更新菜单位置
     *
     * @param x
     * @param y
     * @ author: aXiBa 2013-3-21 下午3:22:18
     */
    private void updateViewPosition(float x, float y) {

        if (x < width_show / 2) {
            Zs4GameData.getInstance().setMenuLeft(true);
        } else {
            Zs4GameData.getInstance().setMenuLeft(false);
        }
        // 更新浮动窗口位置参数
        wmParams.x = (int) (x);
        wmParams.y = (int) (y);
//		LogUtil.i(TAG, "wmParams.x " + wmParams.x + "wmParams.y " + wmParams.y);// 调试信息
        mWindowManager.updateViewLayout(mView, wmParams);
//        setBackground();
    }


    /**
     * function: 调整位置 只放在左边
     *
     * @ author: aXiBa 2013-3-7 下午2:22:30
     */
    private void ajustViewPosition(float x, float y) {

        // 左边
        if (x <= width_show / 2) {
            Zs4GameData.getInstance().setMenuLeft(true);
            if (y <= height_show / 2) {
                updateViewPosition(0, y);
                mDuckType = Zs4GameBase.DUCKPOSITION_LEFTTOP;
            }
            // 下边
            else {
                updateViewPosition(0, y);
                mDuckType = Zs4GameBase.DUCKPOSITION_LEFTBOTTOM;
            }
        }
        // 右
        else {
            Zs4GameData.getInstance().setMenuLeft(false);
            // 上边
            if (y <= height_show / 2) {
                updateViewPosition(width_show, y);
                mDuckType = Zs4GameBase.DUCKPOSITION_RIGHTTOP;
            }
            // 下边
            else {
                updateViewPosition(width_show, y);
                mDuckType = Zs4GameBase.DUCKPOSITION_RIGHTBOTTOM;
            }

        }

//        if (y <= height_show / 2) {
//            mDuckType = Zs4GameBase.DUCKPOSITION_LEFTTOP;
//        }
//        // 下边
//        else {
//            mDuckType = Zs4GameBase.DUCKPOSITION_LEFTBOTTOM;
//        }
//        Zs4GameData.getInstance().setMenuLeft(true);
//        updateViewPosition(0, y);

        refreshFloatMenu();
        setBackground();
        timerForHide();
    }


    public static void setmDuckType(int mDuckType) {
        SDKGameStartMenu.mDuckType = mDuckType;
    }

    public static int getmDuckType() {
        return mDuckType;
    }

    public interface EventHandler {

        // 点击处理
        void clickHandler();
    }
}
